//
//  MusicDetailViewController.m
//  FNer
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 刘志强. All rights reserved.
//

#import "MusicAllDetailViewController.h"
#import "MusicErchDetailModel.h"
#import "MusicPlayerViewController.h"
#import "BaseTableView.h"
#import "MusicDetailTableView.h"
#import "MusicInfo.h"
@interface MusicAllDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,retain)BaseTableView *mytableView;
@property (nonatomic,retain)NSMutableArray *array;
@property (nonatomic,strong)UIScrollView *moveScrollView;
@property (nonatomic, strong)CoreDataManager *coreDataManger;
@property (nonatomic,assign)BOOL isUpLoading;
@property (nonatomic,assign)NSInteger currentPage;
@property (nonatomic,retain)NSArray *myArray;


@end


@implementation MusicAllDetailViewController
{
    MusicPlayerViewController *play;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.mytableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, 0, 375 *XWIDTH, 667 *XHIGHT) style:(UITableViewStylePlain)];
    self.coreDataManger = [CoreDataManager shareManager];
    [self.view addSubview:self.mytableView];
    self.mytableView.delegate = self;
    self.mytableView.dataSource = self;
    self.moveScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(80, 30, 350, 30)];
    self.moveScrollView.delegate = self;
    play = [MusicPlayerViewController sharePlayerDataHandel];
     play.moveLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 350, 30)];
 
    self.array = [NSMutableArray array];
    


    
    [self addHeaderRefresh];
    [self addFooterRefresh];
    
    
    
}


- (void)addHeaderRefresh
{
    self.mytableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isUpLoading =NO;
        
        
        self.currentPage = 1;
        [self getAfn:self.currentPage];

        
    }];
    [self.mytableView.header beginRefreshing];
}



- (void)addFooterRefresh
{
    self.mytableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.isUpLoading =YES;
        //NSLog(@"上拉");
        //上拉一次页码加1
        self.currentPage ++;
        [self getAfn:self.currentPage];

        
    }];
}

- (void)getAfn:(NSInteger)page
{
    NSString *urlste = [NSString stringWithFormat:@"http://echosystem.kibey.com/channel/info?limit=20&id=%@&list_order=hot&page=%ld",self.id,page];
    
    
    
    
    [AFNTools getAFN:urlste andpara:nil andBlock:^(id result) {
        NSDictionary *allDic = result;
        
        if(self.isUpLoading == NO)
        {
            //如果是下拉操作 清空数组
            [self.array removeAllObjects];
            
        }
        
        NSDictionary *resultDic = [allDic objectForKey:@"result"];
        NSDictionary *dataDic = [resultDic objectForKey:@"data"];
        NSArray *soundsArray = [dataDic objectForKey:@"sounds"];
        for (NSDictionary *dic in soundsArray) {
            MusicErchDetailModel *model =[[MusicErchDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];

        }
        [self.mytableView.header endRefreshing];
        [self.mytableView.footer endRefreshing];
        [self.mytableView reloadData];
    } andfailBlock:^(id fail) {
        [self.mytableView.header endRefreshing];
        [self.mytableView.footer endRefreshing];
        
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}


- (void)barAction
{
    MusicPlayerViewController *m = [MusicPlayerViewController sharePlayerDataHandel];
    [self.navigationController pushViewController:m animated:YES];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *colli = @"ning";
    MusicDetailTableView *coll = [tableView dequeueReusableCellWithIdentifier:colli];
    if (coll ==nil) {
        coll = [[MusicDetailTableView alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:colli];
    }
    MusicErchDetailModel *model =[self.array objectAtIndex:indexPath.row];
    coll.model = model;
    
    return coll;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    
    
    if ([self isHaveLocal:play.song_id]) {
        
        MusicInfo *model =[self.myArray objectAtIndex:0];
        //   play.url = model.musicUrl;
        play.url = model.musicLocalUrl;
        play.allMusicArray = self.myArray;
        play.indexRow = indexPath.row;
        play.imageUrl = model.musicImage;
        play.song_id = [model.musicLocalUrl integerValue];
        [SHAREDAPPDELE.myTB isHiddenTabBar:YES withViewController:play];
        // self.moveScrollView.contentSize = CGSizeMake(400, self.moveScrollView.frame.size.height);
        // self.moveScrollView.showsHorizontalScrollIndicator = NO;
        
        // play.moveLabel.text = model.name;
        
        //  [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveAction) userInfo:nil repeats:YES];
        
        
        //    [self.moveScrollView addSubview:play.moveLabel];
        //   play.navigationItem.titleView =  self.moveScrollView;
    //    play.hidesBottomBarWhenPushed = YES;
        [play playLocalMusic];

        
        play.isLocal = YES;
      //  play.url = model.musicLocalUrl;
    }
    else
    {
        MusicErchDetailModel *model =[self.array objectAtIndex:indexPath.row];
        play.song_id = [model.id integerValue];
        play.allMusicArray = self.array;
        play.indexRow = indexPath.row;
        self.moveScrollView.contentSize = CGSizeMake(400, self.moveScrollView.frame.size.height);
        self.moveScrollView.showsHorizontalScrollIndicator = NO;
        
        play.moveLabel.text = model.name;

         play.isLocal = NO;
    }
   
     [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(moveAction) userInfo:nil repeats:YES];
    
 
    [self.moveScrollView addSubview:play.moveLabel];
    play.navigationItem.titleView =  self.moveScrollView;

    [play getData];
    [self.navigationController pushViewController:play animated:YES];
}



- (BOOL)isHaveLocal:(NSInteger )song_id
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MusicInfo" inManagedObjectContext:self.coreDataManger.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"musicName"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    self.myArray = [self.coreDataManger.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (_array == nil) {
        NSLog(@"%@",error);
    }
    else
    {
        
    }
    NSMutableArray *a = [NSMutableArray array];
    for (MusicInfo *m in _myArray) {
        [a addObject:m.musicUrl];
    }
    if ([a containsObject:[NSNumber numberWithInteger:song_id]]) {
        return YES;
    }
    return NO;
    

}



- (void)moveAction
{
    [UIView animateWithDuration:0.05 animations:^{
      
          CGPoint temp = self.moveScrollView.contentOffset;
        if (self.moveScrollView.contentOffset.x > 220/375.00*WIDTH) {
            self.moveScrollView.contentOffset = CGPointMake(-50, 0);
            return ;//停止往下走 类似于break
        }
        self.moveScrollView.contentOffset = CGPointMake(temp.x +2, 0);
        
    }];
}






- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
